package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.InputStream;
import java.util.UUID;

public class FileUtil {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private static final String ENDPOINT = "http://oss-cn-shanghai.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。
    private static final String ACCESS_KEY_ID = "LTAI4G2yzVvSfHn6dhAkM8Pv";
    private static final String ACCESS_KEY_SECRET = "JNsvTrm0UByoUCieRfbXEypPvlALJT";
    //bucket名称
    private static final String BUCKET_NAME = "cz-118";

    public static String upload(InputStream inputStream, String fileName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        String key = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, inputStream);
        // 上传文件。
        ossClient.putObject(putObjectRequest);
        // 关闭OSSClient。
        ossClient.shutdown();
        return key;
    }

    public static boolean delete(String path){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 删除文件
        ossClient.deleteObject(BUCKET_NAME,path);
        // 关闭OSSClient。
        ossClient.shutdown();
        return true;
    }

}
